package com.example.attrimirror.ui.attribute;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ProgressBar;
import android.widget.ImageView;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.graphics.Color;
import android.view.Gravity;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.DiffUtil;

import com.example.attrimirror.R;
import com.example.attrimirror.model.Attribute;

import java.util.List;

public class AttributeAdapter extends ListAdapter<Attribute, AttributeAdapter.ViewHolder> {

    private static final DiffUtil.ItemCallback<Attribute> DIFF_CALLBACK = new DiffUtil.ItemCallback<Attribute>() {
        @Override
        public boolean areItemsTheSame(@NonNull Attribute oldItem, @NonNull Attribute newItem) {
            return oldItem.getId().equals(newItem.getId());
        }

        @Override
        public boolean areContentsTheSame(@NonNull Attribute oldItem, @NonNull Attribute newItem) {
            return oldItem.getLevel() == newItem.getLevel() 
                && Math.abs(oldItem.getExperience() - newItem.getExperience()) < 0.0001;  // 使用小数点比较
        }
    };

    private final OnAttributeUpdateListener updateListener;

    public interface OnAttributeUpdateListener {
        void onAttributeUpdated(Attribute attribute);
    }

    public AttributeAdapter(OnAttributeUpdateListener listener) {
        super(DIFF_CALLBACK);
        this.updateListener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_attribute, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Attribute attribute = getItem(position);
        holder.nameText.setText(attribute.getName());
        holder.descriptionText.setText(attribute.getDescription());

        if (attribute.isPositive()) {
            // 正面属性显示
            holder.levelText.setVisibility(View.VISIBLE);
            holder.layoutProgress.setVisibility(View.VISIBLE);
            holder.imageHammer.setVisibility(View.GONE);
            holder.gridNails.setVisibility(View.GONE);

            holder.levelText.setText("Lv." + attribute.getLevel());
            holder.progressBar.setProgress(attribute.getProgress());
            holder.experienceText.setText(String.format("%.1f/%d", 
                attribute.getExperience(), attribute.getRequiredExperience()));
        } else {
            // 负面属性显示
            holder.levelText.setVisibility(View.GONE);
            holder.layoutProgress.setVisibility(View.GONE);
            holder.imageHammer.setVisibility(View.VISIBLE);
            holder.gridNails.setVisibility(View.VISIBLE);

            // 更新钉子网格
            updateNailGrid(holder.gridNails, attribute);

            // 设置锤子点击事件
            holder.imageHammer.setOnClickListener(v -> {
                attribute.addNail();
                notifyItemChanged(position);
                // 调用回调保存更新
                if (updateListener != null) {
                    updateListener.onAttributeUpdated(attribute);
                }
            });
        }
    }

    private void updateNailGrid(GridLayout grid, Attribute attribute) {
        grid.removeAllViews();
        List<Attribute.NailState> states = attribute.getNailStates();
        List<Long> timestamps = attribute.getNailTimestamps();
        
        grid.setColumnCount(10);
        int rows = (states.size() + 9) / 10;  // 每行10个，计算需要的行数
        grid.setRowCount(Math.max(2, rows));  // 最少2行
        
        long currentTime = System.currentTimeMillis();
        
        // 计算每个钉子的固定宽度（包含间距）
        int screenWidth = grid.getContext().getResources().getDisplayMetrics().widthPixels;
        int gridPadding = dpToPx(grid.getContext(), 16);  // GridLayout的padding
        int availableWidth = screenWidth - (2 * gridPadding);
        int itemWidth = availableWidth / 10;  // 10列均分宽度
        
        // 添加现有的钉子和孔洞
        for (int i = 0; i < states.size(); i++) {
            // 创建包含图标和倒计时的容器
            LinearLayout container = new LinearLayout(grid.getContext());
            container.setOrientation(LinearLayout.VERTICAL);
            container.setGravity(Gravity.CENTER);
            GridLayout.LayoutParams containerParams = new GridLayout.LayoutParams();
            containerParams.width = itemWidth;  // 使用固定宽度
            containerParams.height = GridLayout.LayoutParams.WRAP_CONTENT;
            container.setLayoutParams(containerParams);

            // 创建图标
            ImageView imageView = new ImageView(grid.getContext());
            LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(
                dpToPx(grid.getContext(), 16),
                dpToPx(grid.getContext(), 16)
            );
            imageView.setLayoutParams(imageParams);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

            // 创建倒计时文本
            TextView countdownText = new TextView(grid.getContext());
            LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            );
            countdownText.setLayoutParams(textParams);
            countdownText.setTextSize(10); // 小字号
            countdownText.setGravity(Gravity.CENTER);
            
            // 计算剩余时间
            long timestamp = timestamps.get(i);
            long diffHours = (currentTime - timestamp) / (60 * 60 * 1000);  // 改用小时计算
            
            switch (states.get(i)) {
                case NAIL:
                    imageView.setImageResource(R.drawable.nail);
                    // 显示变成孔的倒计时
                    int nailHoursLeft = 24 - (int)diffHours;
                    if (nailHoursLeft > 1) {
                        countdownText.setText(nailHoursLeft + "小时");
                    } else {
                        // 不足1小时时显示分钟
                        long diffMinutes = (currentTime - timestamp) / (60 * 1000);
                        int minutesLeft = 60 - (int)(diffMinutes % 60);
                        countdownText.setText(minutesLeft + "分钟");
                    }
                    countdownText.setTextColor(Color.RED);
                    break;
                case HOLE:
                    imageView.setImageResource(R.drawable.hole);
                    // 显示消失的倒计时
                    int holeHoursLeft = 96 - (int)diffHours;
                    if (holeHoursLeft > 24) {
                        countdownText.setText((holeHoursLeft / 24) + "天");  // 超过24小时显示天数
                    } else {
                        countdownText.setText(holeHoursLeft + "小时");
                    }
                    countdownText.setTextColor(Color.GRAY);
                    break;
            }
            
            // 将图标和倒计时添加到容器中
            container.addView(imageView);
            container.addView(countdownText);
            
            // 将容器添加到网格中
            grid.addView(container);
        }
    }

    private int dpToPx(Context context, int dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return Math.round(dp * density);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView nameText;
        TextView descriptionText;
        TextView levelText;
        ProgressBar progressBar;
        TextView experienceText;
        ImageView imageHammer;
        GridLayout gridNails;
        LinearLayout layoutProgress;

        ViewHolder(View itemView) {
            super(itemView);
            nameText = itemView.findViewById(R.id.text_attribute_name);
            descriptionText = itemView.findViewById(R.id.text_attribute_description);
            levelText = itemView.findViewById(R.id.text_attribute_level);
            progressBar = itemView.findViewById(R.id.progress_attribute);
            experienceText = itemView.findViewById(R.id.text_attribute_experience);
            imageHammer = itemView.findViewById(R.id.image_hammer);
            gridNails = itemView.findViewById(R.id.grid_nails);
            layoutProgress = itemView.findViewById(R.id.layout_progress);
        }
    }
} 